import os
import json
import datetime
from typing import List, Optional, Dict, Any, Union
from fastapi import APIRouter, Depends, HTTPException, Body, Query
from pydantic import BaseModel
from auth import check_permission, get_current_active_user, fake_db
from rag_chain import RAGChain
from utils import vectorizer  # 从utils.py导入共享的TextVectorizer实例

# 创建管理员路由
admin_router = APIRouter(
    prefix="/admin",
    tags=["admin"],
    dependencies=[Depends(check_permission("admin:manage"))]
)


@admin_router.get("/roles")
async def get_roles():
    # 获取所有角色
    return {
        "roles": fake_db.roles
    }


@admin_router.get("/logs")
async def get_logs(
    start_time: Optional[datetime.datetime] = Query(None),
    end_time: Optional[datetime.datetime] = Query(None),
    level: Optional[str] = Query(None),
    message_contains: Optional[str] = Query(None),
    limit: int = Query(20, ge=1, le=1000),
    offset: int = Query(0, ge=0),
    current_user: Dict[str, Any] = Depends(check_permission("admin:manage"))
):
    # 创建日志筛选条件
    filter = LogFilter(
        start_time=start_time,
        end_time=end_time,
        level=level,
        message_contains=message_contains
    )
    
    # 获取筛选后的日志
    logs = log_store.get_logs(filter=filter, limit=limit, offset=offset)
    total = len(log_store.logs)
    
    return {
        "logs": logs,
        "total": total,
        "limit": limit,
        "offset": offset
    }


@admin_router.delete("/logs")
async def delete_logs(
    current_user: Dict[str, Any] = Depends(check_permission("admin:manage"))
):
    # 清空日志
    result = log_store.clear_logs()
    return result


# 定义Pydantic模型
class UserUpdate(BaseModel):
    username: Optional[str] = None
    email: Optional[str] = None
    password: Optional[str] = None
    is_active: Optional[bool] = None
    role_ids: Optional[List[str]] = None

class ModelConfig(BaseModel):
    deepseek_api_key: Optional[str] = None
    embedding_model: Optional[str] = None
    llm_model: Optional[str] = None
    temperature: Optional[float] = None

class LogFilter(BaseModel):
    start_time: Optional[datetime.datetime] = None
    end_time: Optional[datetime.datetime] = None
    level: Optional[str] = None
    message_contains: Optional[str] = None

# 模拟日志存储 - 实际应用中应使用专业日志系统
class LogStore:
    def __init__(self):
        self.logs = []
        self.log_file = "app.log"
        # 尝试加载现有日志
        self._load_logs()

    def _load_logs(self):
        try:
            if os.path.exists(self.log_file):
                with open(self.log_file, 'r', encoding='utf-8') as f:
                    self.logs = json.load(f)
                    # 将字符串类型的时间戳转换为datetime.datetime对象
                    for log in self.logs:
                        if isinstance(log["timestamp"], str):
                            try:
                                log["timestamp"] = datetime.datetime.fromisoformat(log["timestamp"])
                            except ValueError:
                                print(f"无法解析时间戳: {log["timestamp"]}")
                print(f"成功加载日志文件，共 {len(self.logs)} 条日志")
            else:
                print(f"日志文件 {self.log_file} 不存在，初始化空日志列表")
                self.logs = []
        except Exception as e:
            print(f"加载日志文件失败: {str(e)}")
            self.logs = []

    def _save_logs(self):
        try:
            with open(self.log_file, 'w', encoding='utf-8') as f:
                json.dump(self.logs, f, default=str)
        except Exception as e:
            print(f"保存日志文件失败: {str(e)}")

    def add_log(self, level: str, message: str, source: str = "system"):
        log_entry = {
            "timestamp": datetime.datetime.now(),
            "level": level,
            "message": message,
            "source": source
        }
        self.logs.append(log_entry)
        self._save_logs()
        return log_entry

    def get_logs(self, filter: Optional[LogFilter] = None, limit: int = 100, offset: int = 0) -> List[Dict[str, Any]]:
        filtered_logs = self.logs
        print(f"原始日志数量: {len(self.logs)}")

        # 应用过滤条件
        if filter:
            print(f"应用筛选条件: {filter}")
            print(f"filter.message_contains类型: {type(filter.message_contains)}")
            if filter.start_time:
                filtered_logs = [log for log in filtered_logs if log["timestamp"] >= filter.start_time]
                print(f"应用开始时间筛选后日志数量: {len(filtered_logs)}")
            if filter.end_time:
                filtered_logs = [log for log in filtered_logs if log["timestamp"] <= filter.end_time]
                print(f"应用结束时间筛选后日志数量: {len(filtered_logs)}")
            if filter.level:
                filtered_logs = [log for log in filtered_logs if log["level"] == filter.level]
                print(f"应用日志级别筛选后日志数量: {len(filtered_logs)}")
            if filter.message_contains is not None:
                print(f"message_contains值: '{filter.message_contains}'")
                filtered_logs = [log for log in filtered_logs if filter.message_contains in log["message"]]
                print(f"应用消息包含筛选后日志数量: {len(filtered_logs)}")
        else:
            print("未应用筛选条件")

        # 按时间戳降序排序
        filtered_logs.sort(key=lambda x: x["timestamp"], reverse=True)

        # 应用分页
        result = filtered_logs[offset:offset + limit]
        print(f"返回日志数量: {len(result)}")
        return result

    def clear_logs(self):
        self.logs = []
        self._save_logs()
        return {"success": True, "message": "日志已清空"}

# 初始化日志存储
log_store = LogStore()

# 添加测试日志数据
def add_test_logs():
    # 添加一些测试日志
    log_store.add_log("INFO", "系统启动成功", "main")
    log_store.add_log("WARNING", "磁盘空间不足", "system")
    log_store.add_log("ERROR", "数据库连接失败", "database")
    log_store.add_log("INFO", "用户登录成功", "auth")
    log_store.add_log("INFO", "文档上传成功", "document")
    print("已添加测试日志数据")

# 添加测试日志
try:
    add_test_logs()
except Exception as e:
    print(f"添加测试日志失败: {str(e)}")

# 模拟模型配置存储
class ModelConfigStore:
    def __init__(self):
        self.config_file = "model_config.json"
        self.default_config = {
            "deepseek_api_key": "",
            "embedding_model": "default",
            "llm_model": "default",
            "temperature": 0.7
        }
        self.config = self._load_config()

    def _load_config(self):
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            else:
                return self.default_config
        except Exception as e:
            print(f"加载配置文件失败: {str(e)}")
            return self.default_config

    def _save_config(self):
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.config, f, indent=2)
            return True
        except Exception as e:
            print(f"保存配置文件失败: {str(e)}")
            return False

    def get_config(self) -> Dict[str, Any]:
        return self.config

    def update_config(self, config_updates: Dict[str, Any]) -> Dict[str, Any]:
        # 更新配置
        self.config.update(config_updates)
        # 保存配置
        success = self._save_config()
        if success:
            # 如果API密钥更新了，通知rag_chain
            if "deepseek_api_key" in config_updates and config_updates["deepseek_api_key"]:
                rag_chain.update_api_key(config_updates["deepseek_api_key"])
        return self.config

# 初始化模型配置存储
model_config_store = ModelConfigStore()

# 初始化RAGChain实例
rag_chain = RAGChain(deepseek_api_key=model_config_store.get_config().get("deepseek_api_key", ""))

# 获取管理员路由函数
def get_admin_routes(app):
    app.include_router(admin_router)
    return app

# 管理员路由实现
@admin_router.get("/users")
async def get_users(
    username: Optional[str] = Query(None),
    email: Optional[str] = Query(None),
    is_active: Optional[bool] = Query(None),
    limit: int = Query(100, ge=1, le=1000),
    offset: int = Query(0, ge=0),
    current_user: Dict[str, Any] = Depends(check_permission("admin:manage"))
):
    # 过滤用户 - 确保filtered_users始终是一个列表且元素是字典
    filtered_users = []
    try:
        # 检查fake_db.users的类型并适当处理
        if isinstance(fake_db.users, list):
            filtered_users = fake_db.users
        elif isinstance(fake_db.users, dict):
            # 如果是字典，假设键是用户ID，值是用户对象
            filtered_users = list(fake_db.users.values())
        else:
            # 其他情况，尝试转换为列表
            filtered_users = list(fake_db.users)
    except Exception as e:
        print(f"获取用户数据失败: {str(e)}")
        filtered_users = []
    
    # 确保所有元素都是字典
    filtered_users = [user for user in filtered_users if isinstance(user, dict)]
    
    if username:
        filtered_users = [user for user in filtered_users if "username" in user and username.lower() in user["username"].lower()]
    if email:
        filtered_users = [user for user in filtered_users if "email" in user and email.lower() in user["email"].lower()]
    if is_active is not None:
        filtered_users = [user for user in filtered_users if "is_active" in user and user["is_active"] == is_active]
    
    # 计算总数
    total = len(filtered_users)
    
    # 应用分页 - 确保offset和limit在有效范围内
    end_index = min(offset + limit, total)
    paginated_users = filtered_users[offset:end_index]
    
    return {
        "users": paginated_users,
        "total": total,
        "limit": limit,
        "offset": offset
    }


@admin_router.get("/users/{user_id}")
async def get_user(
    user_id: str,
    current_user: Dict[str, Any] = Depends(check_permission("admin:manage"))
):
    # 查找用户 - 添加错误处理
    try:
        # 打印调试信息
        print(f"尝试查找用户ID: {user_id}")
        print(f"users字典内容: {fake_db.users}")
        
        # 查找用户
        user = next((u for u in fake_db.users.values() if isinstance(u, dict) and u.get("id") == user_id), None)
        
        if not user:
            raise HTTPException(status_code=404, detail=f"用户不存在: {user_id}")
        
        return user
    except Exception as e:
        print(f"获取用户信息异常: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取用户信息异常: {str(e)}")


@admin_router.put("/users/{user_id}")
async def update_user(
    user_id: str,
    user_update: UserUpdate = Body(...),
    current_user: Dict[str, Any] = Depends(check_permission("admin:manage"))
):
    # 查找用户
    user_index = next((i for i, u in enumerate(fake_db.users) if u["id"] == user_id), None)
    
    if user_index is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 更新用户信息
    user = fake_db.users[user_index]
    
    if user_update.username is not None:
        user["username"] = user_update.username
    if user_update.email is not None:
        user["email"] = user_update.email
    if user_update.password is not None:
        # 这里应该加密密码，实际应用中使用密码哈希
        user["password"] = user_update.password  # 注意：实际应用中应该使用密码哈希
    if user_update.is_active is not None:
        user["is_active"] = user_update.is_active
    if user_update.role_ids is not None:
        # 查找角色
        roles = [role for role in fake_db.roles if role["id"] in user_update.role_ids]
        user["roles"] = roles
    
    # 更新用户
    fake_db.users[user_index] = user
    
    return user


@admin_router.delete("/users/{user_id}")
async def delete_user(
    user_id: str,
    current_user: Dict[str, Any] = Depends(check_permission("admin:manage"))
):
    # 查找用户
    user_index = next((i for i, u in enumerate(fake_db.users) if u["id"] == user_id), None)
    
    if user_index is None:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 删除用户
    deleted_user = fake_db.users.pop(user_index)
    
    return {
        "success": True,
        "message": f"用户 {deleted_user['username']} 已删除"
    }


@admin_router.get("/model-config")
async def get_model_config(
    current_user: Dict[str, Any] = Depends(check_permission("admin:manage"))
):
    # 获取模型配置
    return model_config_store.get_config()


@admin_router.post("/model-config")
async def update_model_config(
    config: ModelConfig = Body(...),
    current_user: Dict[str, Any] = Depends(check_permission("admin:manage"))
):
    # 更新模型配置
    config_dict = config.dict(exclude_none=True)
    updated_config = model_config_store.update_config(config_dict)
    
    return updated_config


@admin_router.get("/dashboard")
async def admin_dashboard(current_user: Dict[str, Any] = Depends(check_permission("admin:manage"))):
    # 获取仪表盘数据
    dashboard_data = {
        "dashboard": {
            "user_count": len(fake_db.users),
            "role_count": len(fake_db.roles),
            "permission_count": len(fake_db.permissions),
            "document_count": len(vectorizer.list_documents())
        },
        "recent_logs": log_store.get_logs(limit=10)
    }
    
    return dashboard_data


@admin_router.get("/logs")
async def get_logs(
    start_time: Optional[datetime.datetime] = Query(None),
    end_time: Optional[datetime.datetime] = Query(None),
    level: Optional[str] = Query(None),
    message_contains: Optional[str] = Query(None),
    limit: int = Query(100, ge=1, le=1000),
    offset: int = Query(0, ge=0),
    current_user: Dict[str, Any] = Depends(check_permission("admin:manage"))
):
    # 创建日志过滤器
    filter = LogFilter(
        start_time=start_time,
        end_time=end_time,
        level=level,
        message_contains=message_contains
    )
    
    # 获取过滤后的日志
    logs = log_store.get_logs(filter=filter, limit=limit, offset=offset)
    total = len(log_store.get_logs(filter=filter))
    
    return {
        "logs": logs,
        "total": total,
        "limit": limit,
        "offset": offset
    }


@admin_router.delete("/logs")
async def clear_logs(current_user: Dict[str, Any] = Depends(check_permission("admin:manage"))):
    # 清空日志
    result = log_store.clear_logs()
    return result